import { Response, NextFunction } from "express";
import { verifyToken } from "../utils/jwt";
import type Typings from "../typings";

// 无需权限白名单
const unAuthUrl: string[] = ["/auth/login", "/auth/logout", "/auth/user/add"];

const authMiddle = async (
  req: Typings.Express.ConvertRequest,
  res: Response,
  next: NextFunction
) => {
  const { authorization } = req.headers;

  const requestUrl = req.originalUrl.split("?")[0];

  const isInWhiteList = unAuthUrl.includes(requestUrl);

  // 静态文件无需权限允许查看
  const isPublicFile = req.originalUrl.includes("/public/");

  /**
   * 不在白名单
   * 没有登录状态
   * 不是 public 文件夹里面的资源时
   * 无权限访问
   */
  // 用户失去登录状态，告知用户没有权限进入系统，需要重新登录
  if (!isInWhiteList && !authorization && !isPublicFile) {
    res.status(401).send("当前用户已失去登录状态，请重新登录");
    return;
  }

  if (!isInWhiteList && authorization) {
    try {
      const user = await verifyToken(authorization);
      // jwt 解析后挂在用户信息到 req
      req.loginUser = user || {};
    } catch (err) {
      console.log(err);
      return res.status(401).send();
    }
  }

  next();
};

export default authMiddle;
